package leetcode.code1020;

public class Solution extends Solution1020 {

	private int row;
	private int col;

	@Override
	public int numEnclaves(int[][] grid) {
		row = grid.length;
		col = grid[0].length;
		this.infectRange(grid);
		int ans = 0;
		for (int i = 1; i < row - 1; i++) {
			for (int j = 1; j < col - 1; j++) {
				if (grid[i][j] == 1)
					ans += this.infect(grid, i, j);
			}
		}
		return ans;
	}

	private void infectRange(int[][] grid) {
		for (int i = 0; i < row; i++) {
			this.infect(grid, i, 0);
			this.infect(grid, i, col - 1);
		}
		for (int i = 0; i < col; i++) {
			this.infect(grid, 0, i);
			this.infect(grid, row - 1, i);
		}
	}

	private int infect(int[][] grid, int i, int j) {
		if (i >= 0 && i < row && j >= 0 && j < col && grid[i][j] == 1) {
			grid[i][j] = 2;
			int ans = 1;
			ans += this.infect(grid, i + 1, j);
			ans += this.infect(grid, i - 1, j);
			ans += this.infect(grid, i, j + 1);
			ans += this.infect(grid, i, j - 1);
			return ans;
		}
		return 0;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
	}

}
